import pytest
import yaml
import traceback
import sys, os


# sys.path.append(os.getcwd())


def base_data():
    s = traceback.extract_stack()
    # parametrize装饰器所在的文件的绝对路径
    file_path = s[-2][0]
    # parametrize装饰器所在行号
    line_num = s[-2][1]

    with open(file_path, 'r', encoding="utf-8")as f:
        # 从行号往后读取文件的每一行，找到第一个"def test_"
        for line in f.readlines()[line_num:]:
            if "def test_" in line:
                break

    # 获取parametrize装饰器所在文件的文件名,将test_,换成data_(数据文件名)
    file_path = os.path.split(file_path)[1]  # 去掉路径,取出文件名
    file_path = os.path.splitext(file_path)[0]  # 去掉文件名的后缀
    file_name = "data_" + file_path[5:]  # 将test_,换成data_

    # 获取parametrize装饰器下方修饰的函数名(应该调用的数据文件字典名)
    start = line.index("def ")
    end = line.index("(")
    fun_name = line[start + 4:end]

    # 解析数据
    with open("./data/" + file_name + ".yml", "rb") as f:
        data = yaml.load(f)[fun_name]

        data_list = list()

        for data_dict in data.values():
            # 如果字典中有marks这个key,并且值为xfail,我们认为他是一个预期失败的情况
            if "marks" in data_dict and data_dict["marks"] == "xfail":
                data_dict.pop("marks")
                data_dict = pytest.param(data_dict, marks=pytest.mark.xfail)
                data_list.append(data_dict)
                continue
            data_list.append(data_dict)

        return data_list

class Setting:
    # 获取当前文件路径
    filePath = os.path.dirname(__file__)
    # 获取当前文件的Real path
    fileNamePath = os.path.split(os.path.realpath(__file__))[0]
    # 获取配置文件的路径
    yamlPath = os.path.join(fileNamePath, '../data/a_setting.yaml')
    # 加上 ,encoding='utf-8'，处理配置文件中含中文出现乱码的情况
    f = open(yamlPath, 'r', encoding='utf-8')
    cont = f.read()
    x = yaml.load(cont)

    test = x['TEST']['url_test']
    ipc_test = x['TEST']['ipc_test']
    api_test = x['TEST']['api_test']
    account_id = x['TEST']['account_id']
    user = x['TEST']['user']
    pwd = x['TEST']['pwd']
    ak = x['TEST']['ak']
    sk = x['TEST']['sk']
    app_id = x['TEST']['app_id']
    space_name = x['TEST']['space_name']
    space_id = x['TEST']['space_id']

    ssh_host = x['DB']['ssh_host']
    ssh_port = x['DB']['ssh_port']
    mongodb_host = x['DB']['mongodb_host']
    mongodb_port = x['DB']['mongodb_port']
    DB_username = x['DB']['username']
    DB_pwd = x['DB']['password']
